<template>
  <el-dialog v-el-drag-dialog title="新建流程分类" :visible.sync="visible" :append-to-body="appendToBody" :before-close="onClose">
    <el-form ref="categoryForm" :model="form" :rules="rules" label-width="120px" :disabled="!hasLoaded">
      <el-card>
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="form.categoryName" />
        </el-form-item>
        <el-form-item label="分类编码" prop="code">
          <el-input v-model="form.code" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status">
            <el-option
              v-for="item in optionOfStatus"
              :key="item.dictCode"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
      </el-card>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button v-if="hasLoaded" type="primary" icon="el-icon-check" @click="onSubmit">确 定</el-button>
      <el-button icon="el-icon-close" @click="onClose">关 闭</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { categoryLoad, categorySave } from '@/api/tool/workflow'

export default {
  name: 'CategoryDialog',
  data() {
    return {
      visible: false,
      appendToBody: false,
      hasLoaded: false,
      form: {
        categoryId: undefined,
        categoryName: undefined,
        code: undefined,
        remark: undefined,
        status: undefined
      },
      rules: {
        categoryName: [
          { required: true, message: '分类名称不能为空' }
        ],
        code: [
          { required: true, message: '分类编码不能为空' }
        ]
      },
      optionOfStatus: []
    }
  },
  methods: {
    init(id) {
      this.hasLoaded = false
      this.form.categoryId = id || null
      this.visible = true
      this.$nextTick(() => {
        this.loadForm(id)
        this.getDictData()
      })
    },
    loadForm(id) {
      if (id) {
        categoryLoad({ 'id': id }).then(response => {
          this.form = this.$api.objectUpdate(this.form, response.param)
        }).catch(() => {})
      }
      // 判断当前用户权限
      this.hasLoaded = this.$perm.hasPermissionOr(['flowable:category:edit'])
    },
    getDictData() {
      this.$dictGroup('sys_available_type').then(response => {
        this.optionOfStatus = response
      }).catch(e => {})
    },
    onSubmit() {
      this.$refs.categoryForm.validate(valid => {
        if (valid) {
          categorySave(this.form).then(response => {
            this.$modal.msgSuccess(response.msg)
            this.$emit('confirmForm')
            this.onClose()
          }).catch(() => {})
        }
      })
    },
    onClose() {
      this.$refs.categoryForm.resetFields()
      this.visible = false
    }
  }
}
</script>
